package com.example.jdimust.value;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.jdimust.util.ACache;
import com.example.jdimust.util.Formatting;
import com.example.jdimust.register.NetworkRequest;
import com.example.jdimust.R;
import com.example.jdimust.historydata.HisDataActivity;
import com.example.jdimust.login.LoginActivity;
import com.example.jdimust.upload.UploadAddValueActivity;
import com.example.jdimust.upload.UploadUpdateActivity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.lang.System.exit;

/**
 * Author: MaZongyang
 * Date: 2021/5/19/0019 19:13
 * Description:
 */
public class ValueActivity extends AppCompatActivity {
    private List<Value> ValueList = new ArrayList<>();
    private ACache acache;//缓存框架
    private Button bt_addvalue;
    public static ValueActivity instance;

    @Override
    protected void onResume() {
        super.onResume();
    }





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectCustomSlowCalls() //API等级11，使用StrictMode.noteSlowCode 自定义的耗时调用
                .detectDiskReads() //磁盘读取操作
                .detectDiskWrites() //磁盘写入操作
                .detectNetwork()  //网络操作
                //  .penaltyDialog() //弹出违规提示对话框
                .detectAll()
                .penaltyLog() //在Logcat 中打印违规异常信息
                .build());

        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectAll()
                .detectActivityLeaks()  //Activity泄露
                .detectLeakedSqlLiteObjects()  //泄露的Sqlite对象
                .setClassInstanceLimit(this.getClass(), 1) //检测实例数量
                .penaltyLog()
                .build());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_value);

        Intent intent = getIntent();
        String accounthash = intent.getStringExtra("accounthash");
        String accountname = intent.getStringExtra("accountname");
        String accountid = intent.getStringExtra("accountid");
        String ledgerHash = intent.getStringExtra("ledgerHash");
        System.out.println("已跳转到ValueActivity");
        acache = ACache.get(this);//创建ACache组件
//        acache.put("accountid", accountid);
//        System.out.println(mCache.getAsString("ledgerHash"));
        String getjsontostring = NetworkRequest.getaccount("/GetMessage/value?aid=", acache.getAsString("acaaccountid"), null);
/*        TextView textview = new TextView(this);
        textview.setText(getjsontostring);
        textview.setTextSize(15);
        textview.setTextColor(Color.BLACK);
        textview.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, 100));
        mainLinerLayout.addView(textview);*/
        ListView listView1 = (ListView) findViewById(R.id.lv_valueres);
        bt_addvalue = (Button) findViewById(R.id.bt_add_data);
        bt_addvalue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ValueActivity.this, UploadAddValueActivity.class);
                startActivity(intent);
            }
        });
        Gson gson2 = new Gson();
        ValueBean valuebean = gson2.fromJson(getjsontostring, ValueBean.class);
        String[] tover = new String[valuebean.getResult().size()];
        String[] totype = new String[valuebean.getResult().size()];
        System.out.println("---------------------------\n" + valuebean.getMessage() + "\n-------------------------------");
//        System.out.println(valuebean.getResult().size());
        String[] vk = new String[valuebean.getResult().size()];
        String[] vv = new String[valuebean.getResult().size()];
        int x = 0;
        int y = 0;
        List tocollect = null;
//        System.out.println("\n---------------------------\n"+valuebean.getResult().get(1).getVersions()+"\n-------------------------------");
        for (int i = 0; i < valuebean.getResult().size(); i++) {
            tover[i] = String.valueOf(valuebean.getResult().get(i).getVersions());
        }
        for (ValueBean.ResultDTO resultDTO : valuebean.getResult()) {
            vk[x] = resultDTO.getValueKey();
            List<ValueBean.ResultDTO.VersionsDTO> versions = resultDTO.getVersions();
            List<ValueBean.ResultDTO.VersionsDTO> collect = null;
            System.out.println(resultDTO.getVersions().get(0));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                collect = versions.stream().sorted((o1, o2) -> o2.getVersion() - o1.getVersion()).collect(Collectors.toList());
            }
            ValueVersionBean valueversionbean = gson2.fromJson(collect.get(0).toString(), ValueVersionBean.class);
            String creatime = Formatting.stampToDate(Long.parseLong(valueversionbean.getCreateTime()));
            System.out.println(valueversionbean.getType());
            totype[x] = valueversionbean.getType();
            Value mmvalue = new Value(resultDTO.getValueKey(), valueversionbean.getValue(), creatime);
            ValueList.add(mmvalue);
            ValueAdapter adapter2 = new ValueAdapter(ValueActivity.this, R.layout.value_item, ValueList);
            listView1.setAdapter(adapter2);
            x++;
        }
        listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView viewByaccid = (TextView) view.findViewById(R.id.acc_lv_id);
                TextView viewByLedacchash = (TextView) view.findViewById(R.id.acc_lv_acchash);
                String tocollectstr = String.valueOf(tocollect);
//                System.out.println(tocollectstr);
                Intent intent = new Intent(ValueActivity.this, HisDataActivity.class);
                intent.putExtra("todata", tover[i]);//参数：name、value
                startActivity(intent);
                Toast.makeText(ValueActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
//                finish();
                exit(0);
//                ValueActivity.instance.finish();
            }
        });
        listView1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView2 = (TextView) view.findViewById(R.id.value_lv_valueKey);
                TextView textView3 = (TextView) view.findViewById(R.id.value_lv_value);
//                Intent intent = new Intent(ValueActivity.this, UploadUpdateActivity.class);

                String valuetemp = (String) textView3.getText();
                String valuekeytemp = (String) textView2.getText();
                acache.put("acavalue", valuetemp);
                acache.put("acavaluekey", valuekeytemp);
                acache.put("acatodata", tover[position]);
                acache.put("acatotype", totype[position]);


//                intent.putExtra("value", textView3.getText());//参数：name、value
//                intent.putExtra("valuekey", textView2.getText());//参数：name、value
//                intent.putExtra("todata", tover[position]);//参数：name、value
//                intent.putExtra("totype", totype[position]);//参数：name、value
                startActivity(new Intent(ValueActivity.this, UploadUpdateActivity.class));
                finish();
                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    /**
     * 菜单的点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.chageuser:
                Toast.makeText(this, "正在切换用户！", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(ValueActivity.this, LoginActivity.class);//从SpendingActivity页面跳转至ExpenseProcesActivity页面
                startActivity(intent);
                break;
            default:
                break;
        }

        return true;
    }
}